
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_getx/core/utils/log_utils.dart';


class AutoScrollList extends StatefulWidget {

  const AutoScrollList({Key? key, required this.child, required this.itemCount, required this.controller, required this.offset, this.visibleNum = 3, this.seconds = 5}) : super(key: key);

  final ScrollController controller;
  final double offset;
  final Widget child;
  final int itemCount;
  final int visibleNum; //一屏可见数量
  final int seconds;

  @override
  _AutoScrollListState createState() => _AutoScrollListState();
}

class _AutoScrollListState extends State<AutoScrollList> {

  Timer? _timer;
  int keyIndex = 0;

  @override
  void initState() {
    super.initState();

    widget.controller.addListener(() {
      keyIndex = widget.controller.offset ~/ widget.offset;
      //log('_scrollControlWelfare.position keyIndex = $keyIndex');
    });

    if(widget.itemCount > 0){
      startAnim();
    }
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Listener(
      child: widget.child,
      onPointerDown: (event){
        _timer?.cancel();
      },
      onPointerUp: (event){
        //log('onPointerUp');
        startAnim();
      },
      onPointerCancel: (event){
        //log('onPointerCancel');
        startAnim();
      },
    );
  }

  void startAnim() {
    var len = widget.itemCount;
    if(len > 0){
      _timer = Timer.periodic(Duration(seconds: widget.seconds), (Timer t){
        try {
          var visibleNum = widget.visibleNum; //一屏可见数量
          if(len > visibleNum && len - keyIndex <= visibleNum){
            keyIndex = 0;
          }else {
            keyIndex = ++keyIndex % len;
          }

          //log('keyIndex = $keyIndex');
          widget.controller.animateTo(widget.offset * keyIndex, duration: const Duration(milliseconds: 200), curve: Curves.ease);
        }catch(e){
          lprint(e.toString());
        }
      });
    }
  }


}
